package com.xquant.screen.controller;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: huaiyu.gao -_- -_-
 * @Date: 2021/4/30 14:37
 */
@RestController
@RequestMapping("/r/cms/www/chinamoney/data")
public class forwardController {

    @GetMapping("/currency/{name}")
    public void chartData(HttpServletRequest request, HttpServletResponse response, @PathVariable String name) throws IOException {
        //1.打开浏览器
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //2.声明get请求
        HttpGet httpGet = new HttpGet("http://www.chinamoney.com.cn/r/cms/www/chinamoney/data/currency/"+name);
        //3.发送请求
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
        //4.判断状态码
        String string = null;
        if(httpResponse.getStatusLine().getStatusCode()==200){
            HttpEntity entity = httpResponse.getEntity();
            //使用工具类EntityUtils，从响应中取出实体表示的内容并转换成字符串
            string = EntityUtils.toString(entity, "utf-8");
            System.out.println(string);
        }
        //5.关闭资源
        httpResponse.close();
        httpClient.close();
        response.getWriter().write(string);
    }

    @GetMapping("/bond/{name}")
    public void bond(HttpServletRequest request, HttpServletResponse response, @PathVariable String name) throws IOException {
        //1.打开浏览器
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //2.声明get请求
        HttpGet httpGet = new HttpGet("http://www.chinamoney.com.cn/r/cms/www/chinamoney/data/bond/"+name);
        //3.发送请求
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
        //4.判断状态码
        String string = null;
        if(httpResponse.getStatusLine().getStatusCode()==200){
            HttpEntity entity = httpResponse.getEntity();
            //使用工具类EntityUtils，从响应中取出实体表示的内容并转换成字符串
            string = EntityUtils.toString(entity, "utf-8");
            System.out.println(string);
        }
        //5.关闭资源
        httpResponse.close();
        httpClient.close();
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(string);
    }
}
